package com.woodws.document.interceptor;

import com.woodws.document.annotation.DocAttribute;
import com.woodws.document.annotation.Import;
import com.woodws.util.PathUtil;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.XLSReader;
import org.springframework.core.MethodParameter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by maoxiaodong on 2016/10/27.
 */
public class ImpInterceptor extends HandlerInterceptorAdapter {

    private static ThreadLocal<Map<String, Object>> params = new ThreadLocal<Map<String, Object>>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) o;
        Method method = handlerMethod.getMethod();
        if (method.isAnnotationPresent(Import.class)) {
            Import imp = method.getAnnotation(Import.class);
            Map<String, Object> params = new HashMap<String, Object>();
            MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
            for (MethodParameter parameter : methodParameters) {
                if(parameter.getParameterAnnotation(DocAttribute.class) != null){
                    Object param = parameter.getParameterType().newInstance();
                    params.put(parameter.getParameterName(), param);
                }
            }

            String config = PathUtil.join("/import", imp.value());
            InputStream inputXML = new BufferedInputStream(getClass()
                    .getResourceAsStream(config));
            XLSReader mainReader = ReaderBuilder.buildFromXML(inputXML);
            MultipartFile file = new StandardMultipartHttpServletRequest(request).getFile(imp.attr());
            InputStream inputXLS = file.getInputStream();
            mainReader.read(inputXLS, params);
            this.params.set(params);
        }
        return true;
    }

    public static Object getParam(String name){
        return params.get().get(name);
    }
}
